package cn.youyu.fm.shiro.realm;

import cn.youyu.fm.domain.Role;
import cn.youyu.fm.domain.User;
import cn.youyu.fm.service.IRoleService;
import cn.youyu.fm.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author: mayuanbao
 * @date: 2018-12-20 14:01
 * @description:
 */
public class MyRealm extends AuthorizingRealm {
    @Resource(name = "userService")
    private IUserService userService;
    @Resource(name = "roleService")
    private IRoleService roleService;

    //    shiro授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        Role role = roleService.getRole(user.getRoleId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (role == null || role.getRoleName().equals("")) {
            return null;
        }
        info.addRole(role.getRoleName());
        return info;
    }

    //    shiro认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String name = (String) token.getPrincipal();
//        获取用户
        User user = userService.getUser(name);
        if (user == null) {
            return null;
        }
        if (user.getStatus() == 0) {
            throw new AuthenticationException("用户已停用");
        }
//        盐值
        ByteSource salt = ByteSource.Util.bytes(user.getSalt());
//        如果身份认证验证成功，返回一个AuthenticationInfo
        return new SimpleAuthenticationInfo(user, user.getPassword(), salt, getName());
    }
}
